package com.cjack.frenchexcel.service;

import com.cjack.frenchexcel.config.LayPage;
import com.cjack.frenchexcel.dao.*;
import com.cjack.frenchexcel.model.GoodsModel;
import com.cjack.frenchexcel.model.UserInvoiceModel;
import com.cjack.frenchexcel.table.*;
import com.cjack.frenchexcel.util.ModelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by root on 10/5/19
 */
@Service
public class UserInvoiceService {

    @Autowired
    private UserInvoiceDao dao;


    public List< UserInvoiceModel> list(LayPage page, GoodsModel model) {
        Sort sort = new Sort( Sort.Direction.DESC, "id");
        Example< UserInvoiceTable> example = Example.of( ModelUtils.copySignModel( model, UserInvoiceTable.class));
        Pageable pageable = new PageRequest( page.getPage()-1, page.getLimit(), sort);
        Page< UserInvoiceTable> resultPage = dao.findAll( example, pageable);
        return ModelUtils.copyListModel( resultPage.getContent(), UserInvoiceModel.class);
    }

    public void save( UserInvoiceModel model) {
        UserInvoiceTable table = null;
        if( model.getId() == null){//新增，把model里面的属性全部复制到新的table里面
            table = ModelUtils.copySignModel( model, UserInvoiceTable.class);
        }else{//修改，把model里面的[非空]属性赋值到数据库里面查询的table里面
            table = dao.findOne( model.getId());
            ModelUtils.copySignModel( model, table);
        }
        dao.save( table);
    }

    public void del( String ids){
        List< UserInvoiceTable> tables = new ArrayList<>();
        String[] idArr = ids.split( ",");
        for( String id : idArr){
            UserInvoiceTable table = new UserInvoiceTable();
            table.setId( Long.valueOf( id));
            tables.add( table);
        }
        dao.deleteInBatch( tables);
    }
}
